define(function (require, exports) {
	var $ = require('jquery');
	var util = require('util');
	var pubjs = require('pubjs');
	var view = require('@base/view');
	var dspUtil = require('dspUtil');

	// 基本的checkBoxGroup模块, 拥有搜索、全选功能
	var CheckBoxGroup = view.container.extend({
		init: function (config) {
			config = pubjs.conf(config, {
				'class': 'M-checkBoxGroup',
				'width': 120, // 每一条宽度
				'line_height': '150%', // 行高
				'url': '',
				'param': null,		//请求参数
				'items': null,
				'id': 'id',
				'name': 'name',
				'reqType': 'ajax',
				'async': false, //是否异步加载, 默认同步
				'tplFile': '/tpl/component/checkBoxGroup.html',
				'mul': true,	//支持多选,单选
				'silent': true,	// 是否发消息
				'hasOperator': false,	//是否有操作列
				'fireType': 'key',	// 发送事件时,是发key, 还是对象, //fireType: key, object
				'operator': null,		//操作列自定义
				'prefix': '',	// 生成id的前缀
				'allItem': null,	//代表所有的选择项.
				'hasSearch': false,
				'full': false, //初始化时,是否把所有的值勾上.
				'autoLoad': true,
				'view_model': {
					'width': 120, // 每一条宽度
					'line_height': '150%', // 行高
					'items': [],	//全部项
					'searchItems': [],	//过滤搜索过的项
					'prefix': '',
					'readonly': false,	//是否disable
					'data': [],		//选中的id集合
					'searchData': [],		//搜索 选中的id集合
					'id': '',		//id field name
					'name': '',		//name filed name
					'itemClick': this.vmItemClick.bind(this),
					'itemSearchClick': this.vmItemSearchClick.bind(this),
					'hasOperator': false,
					'hasSearch': false,
					'operator': [],
					'operate': [],	//操作列的选中值.
					'searchMode': false,
					'operateClick': this.vmOperateClick.bind(this)
				}
			});

			this.$param = {};
			this.Super('init', arguments);
		},
		afterBuild: function () {
			var vm = this.vm.$;
			var c = this.getConfig();
			vm['id'] = c.id || 'id';
			vm['name'] = c.name || 'name';
			vm['prefix'] = c.prefix || Math.floor(Math.random() * 10000);
			vm['width'] = c.width;
			vm['line_height'] = c.line_height;
			//单选的话就不要操作列
			if (!c.mul) {
				c.hasOperator = false;
			}
			else if (c.operator) {
				c.hasOperator = true;
			}
			vm['hasOperator'] = c.hasOperator;
			vm['hasSearch'] = c.hasSearch || false;
			vm['operator'] = (c.operator && c.operator.length) ? c.operator : [
				{'name': LANG('全选'), 'id': 'all'}
				, {'name': LANG('反选'), 'id': 'reverse'}
				, {'name': LANG('清空'), 'id': 'empty'}
			];

			this.buildFromTemplate();
		},
		onSearch: function (ev) {
			if (ev.param) {
				// this.vm.$.searchMode = true;
				this.filterItems(ev.param);
			}
			else {
				// this.vm.$.searchMode = false;
				this.vm.$.items = this.$data;
			}
			return false;
		},
		afterBuildTemplate: function () {
			var c = this.getConfig();
			if (c.url && c.autoLoad) {
				this.load();
			} else if (c.items) {
				if (c.allItem) {
					c.items.unshift(c.allItem);
				}
				this.$data = c.items;
				this.vm.$.items = c.items;
				if (c.full) {
					this.setAllValue();
				}
			}
		},
		vmOperateClick: function (oper) {
			var self = this
				, c = this.getConfig()
				, vm = self.vm.$;
			vm.operate = [oper];
			switch (oper) {
				case 'all':
					vm.data = self.selectValue();
					break;
				case 'reverse':
					var nowSelect = vm.data;
					vm.data = self.selectValue(self.$data, function (record) {
						return nowSelect.indexOf(record[vm.id].toString()) == -1;
					});
					break;
				case 'empty':
					vm.data = [];
					break;
			}
			if (!c.silent) {
				self.fire('checkboxClick', self.getValue(c.fireType == 'object'));
			}
		},
		selectValue: function (data, judge) {
			if (!data) {
				data = this.$data;
			}
			var vm = this.vm.$;
			var ret = [];
			util.each(data, function (da) {
				if (judge && util.isFunc(judge)) {
					if (judge(da)) {
						ret.push(da[vm.id].toString());
					}
				}
				else {
					ret.push(da[vm.id].toString());
				}
			});

			return ret;
		},
		setAllValue: function () {
			this.vm.setItem('data', this.selectValue());
			this.fire('checkboxClick', this.getValue(this.getConfig('fireType') == 'object'));
			return this;
		},
		onRemoveCheckBox: function (ev) {
			var data = this.vm.$.data;
			var index = data.indexOf(ev.param);
			data.splice(index, 1);
			return false;
		},
		vmItemSearchClick: function (value) {
			var self = this
				, vm = self.vm.$;
			if (vm.searchData.indexOf(value) == -1) {
				//删除
				var index = vm.data.indexOf(value);
				if (index > -1) {
					vm.data.splice(index, 1);
				}
			}
			else {
				//添加
				vm.data.push(value);
			}

		},
		vmItemClick: function (value) {
			var c = this.getConfig();
			var vm = this.vm.$;
			if (!c.mul) {
				vm.data = [value.toString()];
			}

			if (!c.silent) {
				var param = [];
				if (c.fireType == 'object') {
					var items = this.vm.getItem('items');
					util.each(items, function (item) {
						if (item[vm.id] == value.toString()) {
							param.push(item);
						}
					});
				}
				else {
					param.push(value);
				}
				this.fire('checkboxClick', param);
			}
			return false;
		},
		load: function (param) {
			var c = this.getConfig();
			if (c.url) {
				if (!c.async) {
					pubjs.sync(null);
				}
				if (c.reqType === 'ajax') {
					pubjs.data.get(c.url, $.extend({}, param, c.param), this);
				}
				else if (c.reqType === 'websocket') {
					pubjs.mc.send(
						c.url,
						$.extend({}, this.$param, c.param),
						this.onData.bind(this)
					);
				}
			}
		},
		loadCb: function (cb) {
			var c = this.getConfig();
			var self = this;
			if (c.url) {
				if (!c.async) {
					pubjs.sync(null);
				}
				pubjs.mc.send(
					c.url,
					$.extend({}, this.$param, c.param),
					function (err, data) {
						self.onData(err, data);
						cb();
					}
				);
			}
		},
		onData: function (err, data) {
			var c = this.getConfig();
			if (!c.async) {
				pubjs.sync(true);
			}
			if (err) {
				pubjs.error(err);
				return false;
			}
			if (data.items) {
				data = data.items;
			}
			if (c.allItem) {
				data.unshift(c.allItem);
			}
			this.vm.$.items = this.$data = data;
			if (c.full && !this.vm.$.data.length) {
				this.setAllValue();
			}
		},
		getValue: function (bool) {
			// bool  true: 返回name id, false返回id.
			var data = this.vm.getItem('data');
			var id = this.vm.getItem('id');
			var ret = [];
			var items = this.vm.getItem('items');
			// 如果items 未拉回来，且返回Id的话，直接返回data
			if ((!items || !items.length) && !bool) {
				return data;
			}

			util.each(items, function (v) {
				if (data.indexOf(v[id].toString()) > -1) {
					ret.push(bool ? v : v[id]);
				}
			});

			return ret;
		},
		setData: function (data) {
			this.vm.$.items = this.$data = data;
			return this;
		},
		getData: function () {
			return this.$data;
		},
		setValue: function (data) {
			if (data && data.length) {
				this.vm.$.data = dspUtil.map(data, String);
			}
			else {
				this.vm.$.data = [];
			}
		},
		getDesc: function(data){
			var self = this;
			data = data || self.getValue();
			var el = self.getDOM();
			var result = [];
			util.each(data, function(item){
				var name = el.find('input[value="'+item+'"]').next().text();
				if(name){
					result.push(name);
				}
			});

			return result;
		},
		reset: function () {
			var c = this.getConfig();
			if (c.full) {
				this.setAllValue();
			}
			else {
				this.vm.$.data = [];
			}
			return this;
		},
		setParam: function (param) {
			this.$param = util.extend(this.$param, param);
			return this;
		},
		setViewMode: function (view) {
			this.vm.setItem('readonly', !!view);
			return this;
		},
		// 过滤选项(在父模块调用)
		filterItems: function (val) {
			var data = this.$data;
			var vm = this.vm.$;
			var newData = [];
			var len = data.length;
			var name = this.getConfig('name');
			var i = 0;
			for (; i < len; i++) {
				var item = data[i][name].toLowerCase();
				var key = val.toLowerCase();
				if (item.indexOf(key) != -1) {
					newData.push(data[i]);
				}
			}
			// vm.searchItems = newData;
			// vm.searchData = vm.data;

			// 搜索结果直接更新items，不用切换到搜索模式
			vm.items = newData;
		}
	});
	exports.base = CheckBoxGroup;

});